﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Cn.Cellula.App.Lib.MiniTop;
using System.Reflection;

namespace Cn.Cellula.MiniTop {
    public partial class FrmDefault : Form {
        public static Common.Logging.ILog log = Common.Logging.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private Int32 _offsetWidth = 0;
        private Int32 _offsetHeight = 0;
        private Boolean _AutoFixed = false;
        public static FrmDefault frmInstance = null;
        MySetting ms = MySetting.CreateInstance();
        public static Int32 LoadTimes = 0;
        public FrmDefault() {
            InitializeComponent();

            this.TopMost = (ms.Get(AppKey.OnTop)!="no");

            //绑定事件
            this.wb_main.Navigating += new WebBrowserNavigatingEventHandler(OnNavigating);
            this.wb_main.Navigated += new WebBrowserNavigatedEventHandler(OnNavigated);
            this.wb_main.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(OnDocumentCompleted);
            
            //定时器
            if (ms.Get(AppKey.AlertTimerEanbled) == "yes" 
                && ms.Get(AppKey.AlertInvokeJs)!=""
                && ms.Get(AppKey.AlertTimerMinutes)!="") {
                this.timer1.Enabled = true;
                this.timer1.Interval = Convert.ToInt32(ms.Get(AppKey.AlertTimerMinutes)) * 1000 * 60;
                this.timer1.Start();
                this.timer1.Tick +=new EventHandler(timer1_Tick);
            }
            this.wb_main.ObjectForScripting = frmInstance;
        }
        private void FrmDefault_Shown(object sender, EventArgs e) {
            //自动最小化
            if (LoadTimes<1 && ms.Get(AppKey.AutoHide) == "yes") {
                this.FrmHide();
            }
            //滚动条
            this.wb_main.ScrollBarsEnabled = (ms.Get(AppKey.EnableScroll) == "yes");

            //窗体大小属性
            _offsetHeight = this.Height - this.wb_main.Height;
            _offsetWidth = this.Width - this.wb_main.Width;
            this.tssl_size.Text = this.Width + ":" + this.Height;

            //窗体大小
            if (ms.Get(AppKey.AutoFixFormSize) != "yes") {
                String w = ms.Get(AppKey.MainFormWidth);
                String h = ms.Get(AppKey.MainFormHeight);
                if (!String.IsNullOrEmpty(w) && !String.IsNullOrEmpty(h)
                    && (w != this.Width.ToString() || h != this.Height.ToString())
                    ) {
                    try {
                        this.Width = Convert.ToInt32(w);
                        this.Height = Convert.ToInt32(h);
                    } catch { }
                }
            }

        }
        public static FrmDefault GetInstance() {
            if (frmInstance == null) frmInstance = new FrmDefault();
            return frmInstance;
        }

        protected void timer1_Tick(Object sender, EventArgs e) {
            MySetting ms = MySetting.CreateInstance();
            String js = ms.Get(AppKey.AlertInvokeJs);
            if (!String.IsNullOrEmpty(js)) {
                String args = ms.Get(AppKey.AlertInvokeJsArgs);
                if (String.IsNullOrEmpty(args)) {
                    this.wb_main.Document.InvokeScript(js);
                } else {
                    this.wb_main.Document.InvokeScript(js, args.Split(','));
                }
            }
        }

        private void NavigateTo(String rUrl) {
            this.wb_main.Navigate(MySetting.CreateInstance().GetLoginUrl());
        }

        #region 窗体隐藏和显示
        public void FrmHide() {
            this.Visible = false;
            this.notifyIcon1.Visible = true;
            this.WindowState = FormWindowState.Minimized;
        }
        public void FrmShow() {
            if (!this.Visible) {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }
        }
        #endregion

        #region 响应窗体事件
        private void OnNavigating(Object sender, WebBrowserNavigatingEventArgs args) {
            this.tssl_Info.Text = "页面加载中...";
        }
        private void OnNavigated(Object sender, WebBrowserNavigatedEventArgs args) {
        }
        private void OnDocumentCompleted(Object sender, WebBrowserDocumentCompletedEventArgs args) {
            this.tssl_Info.Text = "完成";
            if (_AutoFixed) {
                this.tssl_size.Text = this.Width + ":" + this.Height;
            } else {
                MySetting ms = MySetting.CreateInstance();
                String autoFix = ms.Get(AppKey.AutoFixFormSize);
                if (autoFix == "yes") {
                    try {
                        HtmlElement body = wb_main.Document.Body;
                        String oldSize = this.Width + ":" + this.Height;
                        Int32 width = Convert.ToInt32(body.GetAttribute("offsetWidth")) + 17 + _offsetWidth;
                        Int32 height = Convert.ToInt32(body.GetAttribute("offsetHeight")) + _offsetHeight;
                        this.Width = (width < 100) ? 100 : width;
                        this.Height = (height < 100) ? 100 : height;
                        this.tssl_size.Text = oldSize + " TO " + this.Width + ":" + this.Height;
                    } catch (Exception ex) {
                        log.Error(ex.Message);
                        MessageBox.Show(ex.Message);
                    }
                    _AutoFixed = true;
                }
            }
        }
        #endregion

        #region 窗体基本事件处理
        
        private void FrmDefault_Load(object sender, EventArgs e) {

            String title = MySetting.CreateInstance().Get(AppKey.FormTitle);
            this.Text = (String.IsNullOrEmpty(title)) ? MySetting.FORM_TITLE : title;

            String url = MySetting.CreateInstance().GetLoginUrl();
            if (String.IsNullOrEmpty(url))
                url = MySetting.HOST_ADDRESS;
            NavigateTo(url);

        }
        

        private void tsmi_Settings_Click(object sender, EventArgs e) {
            FrmSetting fs = FrmSetting.GetInstance();
            DialogResult dr = fs.ShowDialog();
        }

        private void tsmi_Close_Click(object sender, EventArgs e) {
            DialogResult dr = MessageBox.Show("确定要关闭?", "INFO", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes) {
                this.Close();
            }
        }

        private void tsmi_Hidden_Click(object sender, EventArgs e) {
            FrmHide();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) {
            FrmShow();
        }
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) {
            FrmShow();
        }

        private void tsmi_ReLogin_Click(object sender, EventArgs e) {
            NavigateTo(MySetting.CreateInstance().GetLogoutUrl());
        }

        private void tsmi_Logout_Click_1(object sender, EventArgs e) {
            NavigateTo(MySetting.CreateInstance().GetLogoutUrl());
        }

        private void tsmi_Reload_Click(object sender, EventArgs e) {
            this.wb_main.Refresh(WebBrowserRefreshOption.Completely);

        }
        private void tsmi_GotoHomeSite_Click(object sender, EventArgs e) {
            //MySetting ms = MySetting.CreateInstance();
            //String url = ms.Get(AppKey.MasterAddress);
            //if(String.IsNullOrEmpty(url)){
            //    url = MySetting.MASTER_ADDRESS;
            //}
            Help.ShowHelp(this, MySetting.MASTER_ADDRESS);
            this.WindowState = FormWindowState.Minimized;
        }
        #endregion

        private void FrmDefault_KeyDown(object sender, KeyEventArgs e) {
            MessageBox.Show(e.KeyCode.ToString() + "," + e.KeyData.ToString() + "," + e.KeyValue);
        }



        


    }
}
